import re
from odoo import api, fields, models, tools, _
from odoo.osv import expression
from dateutil.relativedelta import relativedelta

class ProductTemplate(models.Model):
    _inherit = "product.template"
    
    default_code2=fields.Char('料号')
    product_name=fields.Char('Description',compute='_compute_product_name')

    @api.depends('default_code2')
    def _compute_product_name(self):
        for r in self:
            r.product_name='%s%s' %(r.default_code2 and '[%s]'% (r.default_code2) or '',r.name and '%s' % (r.name) or '') 


class ProductProduct(models.Model):
    _inherit = 'product.product'
    # 如果只显示default_code，在创建发票等没有default_code只有name时，操作不方便，只在打印的模板里调整，只显示default_code而不显示"[default_code]name"。
    # @api.multi
    # def name_get(self):
    #     return [(p.id,"%s" % (p.default_code and '%s' % (p.default_code) or '')) for p in self]

    @api.model #继承方法
    def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
        if not args:
            args = []
        if name:
            positive_operators = ['=', 'ilike', '=ilike', 'like', '=like']
            product_ids = []
            if operator in positive_operators:
                product_ids = self._search([('default_code', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid)
                if not product_ids: #dbh 增加在订单中查找default_code2
                    product_tmpl_ids=self.env['product.template'].search([('default_code2', '=', name)]).ids
                    product_ids = self._search([('product_tmpl_id', 'in', product_tmpl_ids)] + args, limit=limit, access_rights_uid=name_get_uid)
                    if not product_ids:
                        product_ids = self._search([('barcode', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid)
            if not product_ids and operator not in expression.NEGATIVE_TERM_OPERATORS:
                # Do not merge the 2 next lines into one single search, SQL search performance would be abysmal
                # on a database with thousands of matching products, due to the huge merge+unique needed for the
                # OR operator (and given the fact that the 'name' lookup results come from the ir.translation table
                # Performing a quick memory merge of ids in Python will give much better performance
                product_ids = self._search(args + [('default_code', operator, name)], limit=limit)
                if not limit or len(product_ids) < limit:
                    # we may underrun the limit because of dupes in the results, that's fine
                    limit2 = (limit - len(product_ids)) if limit else False
                    product2_ids = self._search(args + [('name', operator, name), ('id', 'not in', product_ids)], limit=limit2, access_rights_uid=name_get_uid)
                    product_ids.extend(product2_ids)
            elif not product_ids and operator in expression.NEGATIVE_TERM_OPERATORS:
                domain = expression.OR([
                    ['&', ('default_code', operator, name), ('name', operator, name)],
                    ['&', ('default_code', '=', False), ('name', operator, name)],
                ])
                domain = expression.AND([args, domain])
                product_ids = self._search(domain, limit=limit, access_rights_uid=name_get_uid)
            if not product_ids and operator in positive_operators:
                ptrn = re.compile('(\[(.*?)\])')
                res = ptrn.search(name)
                if res:
                    product_ids = self._search([('default_code', '=', res.group(2))] + args, limit=limit, access_rights_uid=name_get_uid)
            # still no results, partner in context: search on supplier info as last hope to find something
            if not product_ids and self._context.get('partner_id'):
                suppliers_ids = self.env['product.supplierinfo']._search([
                    ('name', '=', self._context.get('partner_id')),
                    '|',
                    ('product_code', operator, name),
                    ('product_name', operator, name)], access_rights_uid=name_get_uid)
                if suppliers_ids:
                    product_ids = self._search([('product_tmpl_id.seller_ids', 'in', suppliers_ids)], limit=limit, access_rights_uid=name_get_uid)
        else:
            product_ids = self._search(args, limit=limit, access_rights_uid=name_get_uid)
        return self.browse(product_ids).name_get()

    def get_product_multiline_description_sale(self): #继承方法
        """ Compute a multiline description of this product, in the context of sales
                (do not use for purchases or other display reasons that don't intend to use "description_sale").
            It will often be used as the default description of a sale order line referencing this product.
        """
        # 设置sale.order.line.name默认取product_name(即[default_code2]product.product.name).而product_id显示[default_code]product.product.name.
        # name = self.display_name
        name = self.product_name #dbh
        if self.description_sale:
            name += '\n' + self.description_sale

        return name

    # @api.multi #继承方法
    # def _select_seller(self, partner_id=False, quantity=0.0, date=None, uom_id=False, params=False):
    #     self.ensure_one()
    #     if date is None:
    #         date = fields.Date.context_today(self)
    #     precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')

    #     res = self.env['product.supplierinfo']
    #     sellers = self._prepare_sellers(params)
    #     if self.env.context.get('force_company'):
    #         sellers = sellers.filtered(lambda s: not s.company_id or s.company_id.id == self.env.context['force_company'])
    #     for seller in sellers:
    #         # Set quantity in UoM of seller
    #         quantity_uom_seller = quantity
    #         if quantity_uom_seller and uom_id and uom_id != seller.product_uom:
    #             quantity_uom_seller = uom_id._compute_quantity(quantity_uom_seller, seller.product_uom)

    #         if seller.date_start and seller.date_start > date + relativedelta(days=int(seller.delay)): #dbh
    #             continue
    #         if seller.date_end and seller.date_end < date + relativedelta(days=int(seller.delay)): #dbh
    #             continue
    #         if partner_id and seller.name not in [partner_id, partner_id.parent_id]:
    #             continue
    #         if float_compare(quantity_uom_seller, seller.min_qty, precision_digits=precision) == -1:
    #             continue
    #         if seller.product_id and seller.product_id != self:
    #             continue

    #         res |= seller
    #         break
    #     return res


class SupplierInfo(models.Model):
    _inherit = "product.supplierinfo"
    _order = 'name,id desc,min_qty desc, price'
    date_revised = fields.Date('价格更新日期') 